package controller

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"gin/common"
	"gin/response"
	"gin/service"
	"gin/tai/voice"
	"gin/validate"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"io"
	"io/ioutil"
	"os"
)

// 语音转文字
func VoiceTransferToText(ctx *gin.Context) {
	var v validate.VoiceTransferToText
	err := ctx.ShouldBind(&v)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	requestUUid := uuid.NewV4().String()
	projectId := uint64(0)
	var sourceType uint64
	fileExt := ""
	Url := ""
	fContentStr := ""
	fLength := int64(0)

	if v.Type == "formData" {
		sourceType = 1
		file, fh, err := ctx.Request.FormFile(v.FileKey)
		if err != nil {
			response.Fail(ctx, nil, err.Error())
			return
		}
		defer file.Close()
		fcBytes, err := ioutil.ReadAll(file)
		if err != nil {
			response.Fail(ctx, nil, err.Error())
			return
		}
		fContentStr = base64.StdEncoding.EncodeToString(fcBytes)
		fileExt = common.GetFileExt(fh.Filename)
		fLength = fh.Size

		md5Str := md5.New()
		_, _ = io.Copy(md5Str, file)
		requestUUid = hex.EncodeToString(md5Str.Sum(nil))
	} else if v.Type == "url" {
		Url = v.Url
		fileExt = v.UrlFileExt
		requestUUid = common.GenerateMd5(Url)
	} else if v.Type == "media" {
		sourceType = 1
		media, err := service.FindMedia(common.Filter{Filter: map[string]interface{}{
			"-eq": map[string]interface{}{
				"condition": "id = ?",
				"val":       v.MediaId,
			}}})
		if err != nil {
			response.Fail(ctx, nil, err.Error())
			return
		}

		if media.Type != "audio" {
			response.Fail(ctx, nil, "[media] type is not audio")
			return
		}

		workDir, _ := os.Getwd()
		fcBytes, err := ioutil.ReadFile(workDir + media.RelativePath)
		if err != nil {
			response.Fail(ctx, nil, "[media] "+err.Error())
			return
		}
		var metaData validate.MediaMetadata
		_ = json.Unmarshal(media.Param, &metaData)
		fileExt = metaData.Ext
		fContentStr = base64.StdEncoding.EncodeToString(fcBytes)
		fLength = int64(len(fcBytes))
		requestUUid = media.Uuid

	}

	resp, err := voice.SentenceRecognition(projectId, sourceType, requestUUid, fileExt, Url, fContentStr, fLength)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	response.Success(ctx, gin.H{"data": resp.Response}, "success")
	return
}
